<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.categories');
jimport('joomla.application.component.modellist');

/**
 * Category Model
 */
class ProductModelCategory extends JModelList
{
	protected $_category;
	protected $_children_ids;

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * return	void
	 * @since	1.6
	 */
	protected function populateState($ordering = null, $direction = null) {
		parent::populateState($ordering, $direction);
		
		// Initialise variables.
		$this->setState('list.limit', 8);
		$this->setState('list.start', JRequest::getUInt("start"));
		
		$catid = JRequest::getVar('catid', 0, '', 'int');
		$this->setState('category.id', $catid);
	}
	
	/**
	 * Method to build an SQL query to load the list data.
	 *
	 * @return	string	An SQL query
	 * @since	1.6
	 */
	function getListQuery() {
		// Create a new query object.
		$db		= $this->getDbo();
		$query	= $db->getQuery(true);
		
		$query->select('*');
		$query->from('#__product');

		$this->getCategory();
		
		// Filter by category.
		if ($catid = $this->getState('category.id')) {
			$query->where('catid IN (' . implode(',', $this->_children_ids) . ')');
		}
				
		// Filter by state
		$query->where('published = 1');

		// TODO Filter by start and end dates.

		// Set sortname ordering if selected
		$query->order('modified DESC');
		
		return $query;
	}
	
	/**
	 * Method to get category data for the current category
	 *
	 * @param	int		An optional ID
	 *
	 * @return	object
	 * @since	1.5
	 */
	public function getCategory()
	{
		if(!is_object($this->_category)) {
			$app = JFactory::getApplication();
			
			$categories = JCategories::getInstance('Product');
			$this->_category = $categories->get($this->getState('category.id', 'root'));
			if (is_object($this->_category)) {
				$children = $this->_category->getChildren(true);
				$this->_children_ids = array(0 => $this->_category->id);
				foreach($children as $i => $child) {
					$this->_children_ids[$i + 1] = $child->id;
				}
			}
		}
	
		return $this->_category;
	}
}